<!--关键词设置-->
<template>
  <div class="ele-body">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="left"
      label-width="110px"
      @keyup.enter.native="submit"
      @submit.native.prevent
    >
      <el-card>
        <div class="keyword-title">关键词设置</div>
        <div class="set-hint">
          新增完成的SEO关键词会进入关键词词库列表内。<br>
          1.关键词标题必填<br>
          2.必须要选择相关组词策略，通过组词策略智能生成SEO文案<br>
          3.区域、词头、主词、长尾词这些内容选择后不能为空,并且不要以逗号结尾
        </div>
        <div class="content">
          <div class="flex-between">
            <el-form-item label="关键词标题" prop="taticsName">
              <el-input
                v-model="form.taticsName"
                placeholder="请输入标题"
                clearable
              />
            </el-form-item>
            <el-radio-group v-model="form.platform" :disabled="$route.query.form ? true : false">
              <el-radio :label="1">D音</el-radio>
              <el-radio :label="2">K手</el-radio>
              <!--视频号隐藏修改，需展示-->
              <!--<el-radio :label="3">视频号</el-radio>-->
            </el-radio-group>
          </div>

          <el-form-item label="选择组词策略" prop="tatics">
            <el-checkbox-group v-model="form.tatics" class="flex-wrap width100" @change="handleCheckedCitiesChange">
              <el-col v-for="(i,j) in taticsList" :key="j" :xs="12" :sm="10" :md="6" :lg="4" >
                <el-checkbox  :label="i.id">{{i.name}}</el-checkbox>
              </el-col>
            </el-checkbox-group>
          </el-form-item>

          <el-row type="flex" justify="space-between">
            <el-col class="el-width flex-column">
              <div class="key-border">
                <div class="content-title flex-column">
                  <div>区域</div>
                  <div>(根据推广区域选择)</div>
                </div>
                <el-input
                  :disabled="form.tatics==3 || form.tatics==4 || form.tatics==5 || form.tatics==7 ? false : true"
                  readonly
                  class="input-size default"
                  :rows="12"
                  type="textarea"
                  v-model="form.region"
                  clearable
                />
              </div>
              <el-button :type="form.tatics==3 || form.tatics==4 || form.tatics==5 || form.tatics==7 ? 'primary' : ''" @click="addCity"
                         :disabled="form.tatics==3 || form.tatics==4 || form.tatics==5 || form.tatics==7 ? false : true">插入城市</el-button>
            </el-col>
            <el-col class="el-width flex-column">
              <div class="key-border">
                <div class="content-title flex-column">
                  <div>词头</div>
                  <div>(插入默认词,多个以英文逗号分开)</div>
                </div>
                <el-input
                  :disabled="form.tatics==1 || form.tatics==4 || form.tatics==6 || form.tatics==7 ? false : true"
                  class="input-size"
                  :rows="12"
                  type="textarea"
                  v-model="form.head"
                  clearable
                />
              </div>
              <el-button
                :type="form.tatics==1 || form.tatics==4 || form.tatics==6 || form.tatics==7 ? 'primary' : ''" @click="prefixClick()"
                :disabled="form.tatics==1 || form.tatics==4 || form.tatics==6 || form.tatics==7 ? false : true">插入默认词头</el-button>
            </el-col>
            <el-col class="el-width">
              <div class="key-border">
                <div class="content-title flex-column">
                  <div>主词</div>
                  <div>(建议20个以内，多个以英文逗号分开)</div>
                </div>
                <el-input
                  class="input-size"
                  :rows="12"
                  type="textarea"
                  v-model="form.body"
                  clearable
                />
              </div>
            </el-col>
            <el-col class="el-width flex-column">
              <div class="key-border">
                <div class="content-title flex-column">
                  <div>长尾词</div>
                  <div>(建议20个以内,多个以英文逗号分开)</div>
                </div>
                <el-input
                  :disabled="form.tatics==2 || form.tatics==5 || form.tatics==6 || form.tatics==7 ? false : true"
                  class="input-size"
                  :rows="12"
                  type="textarea"
                  v-model="form.suffix"
                  clearable
                />
              </div>
              <el-button
                :type="form.tatics==2 || form.tatics==5 || form.tatics==6 || form.tatics==7 ? 'primary' : ''"
                @click="endClick()"
                :disabled="form.tatics==2 || form.tatics==5 || form.tatics==6 || form.tatics==7
                 ? false : true">插入默认长尾词</el-button>
            </el-col>
            <el-col class="el-width flex-column" v-if="form.platform==1 || form.platform==3 ">
              <div class="key-border">
                <div class="content-title flex-column">
                  <div>话题</div>
                  <div>(格式：#话题1,#话题2)</div>
                </div>
                <div class="all-hashtag">

                  <!--                <div :style="hashtagList.length<=0 ? 'height: 261px;' : ''">-->
                  <div v-for="(i,j) in hashtagList" :key="j" class="relative">
                    <div
                      class="input-hashtag font-overflow" @click="lookTag(hashtagList[j],j)">{{hashtagList[j]}}</div>
                    <i class="el-icon-edit edit-hashtag flex" @click="lookTag(hashtagList[j],j)"></i>
                    <i class="el-icon-close del-hashtag flex" @click="delTag(j)"></i>
                    <!--<el-input
                      :disabled="true"
                      class="input-hashtag"
                      v-model="hashtagList[j]"
                      clearable
                    >

                    <template slot="append">
                      <i class="el-icon-edit"></i>
                      <i class="el-icon-close"></i>
                    </template>
                    </el-input>-->
                    <!--<el-input
                      class="input-size"
                      :rows="12"
                      type="textarea"
                      v-model="form.hashtag"
                      clearable
                    />-->
                  </div>
                </div>
              </div>
              <el-button type="primary" @click="addTitle()">添加话题组</el-button>
            </el-col>
          </el-row>
        </div>
        <el-button class="save-btn flex" @click="save()">
          确定保存
        </el-button>
      </el-card>
    </el-form>
    <!--选择默认词头-->
    <prefix
      ref="prefixShow"
      :list="prefixList"
      :type="type"
      :oldList="form.head"
      @checkedAll="checkedAll"
    ></prefix>
    <!-- 词尾 -->
    <prefix
      ref="prendShow"
      :list="endList"
      :type="type"
      :oldList="form.suffix"
      @checkedAll="endAll"
    ></prefix>

    <areaList
      ref="citys"
      :visible.sync="areaShow"
      :list="cityList"
      :oldList="form.provinceList"
      @cityClick="cityClick">
    </areaList>

    <add-topic
      ref="addShow"
      @topicClick="hashtagClick"></add-topic>
  </div>
</template>
<script>
  import {areaAll, seodefaultList, addSeo,updateSeo} from "@/api/matrixManage/seo";
  import prefix from './components/prefix.vue';
  import prend from './components/prend.vue';
  import areaList from "@/views/matrixManage/seoCopy/keywordSet/components/areaList";
  import AddTopic from "@/views/matrixManage/seoCopy/keywordSet/components/addTopic";
  export default {
    name: "index",
    components:{AddTopic, areaList, prefix, prend},
    data() {
      return {
        hashtagList:[],//话题list
        // ‘城市’ 数据
        cityList:[],
        // ‘城市’ 弹出框
        areaShow:false,
        isClick:false,
        // 组词策略 List
        taticsList:[
          {
            id:1,
            name:'词头+主词'
          },
          {
            id:2,
            name:'主词+长尾词'
          },
          {
            id:3,
            name:'区域+主词'
          },
          {
            id:4,
            name:'区域+词头+主词'
          },
          {
            id:5,
            name:'区域+主词+长尾词'
          },
          {
            id:6,
            name:'词头+主词+长尾词'
          },
          {
            id:7,
            name:'区域+词头+主词+长尾词'
          }
        ],
        form: {
          platform:1,
          head:'',
          suffix:'',
          username:this.$store.state.user.info.username,
          tatics: [],
          // provinceList:[],
          /*provinceList:[{
            areaCode: "110000",
            areaId: 1,
            areaName: "北京",
            checked: null,

            country: [{
              areaCode: "110100",
              areaId: 427,
              areaName: "北京市",
              checked: null,
              createTime: "2023-03-04T15:26:53.000+00:00",
              creator: "admin",
              dbSortType: null,
              endTime: null,
              ids: null,
              level: "2",
              limit: null,
              page: null,
              parentId: 1,
              selected: true,
              sortFields: null,
              startTime: null,
              updateTime: "2023-03-04T15:26:53.000+00:00",
            }],
            createTime: "2023-03-04T15:13:23.000+00:00",
            creator: "admin",
            dbSortType: null,
            endTime: null,
            ids: null,
            isIndeterminate: false,
            level: "1",
            limit: null,
            page: null,
            parentId: 0,
            // indeterminate:false, 是否子级选中的
            selected: true,  // 是否选中
            sortFields: null,
            startTime: null,
            updateTime: "2023-03-04T15:13:23.000+00:00",
          },
            {
              areaCode: "130000",
              areaId: 1,
              areaName: "河北省",
              checked: null,
              country: [{
                areaCode: "130200",
                areaId: 427,
                areaName: "唐山市",
                checked: null,
                createTime: "2023-03-04T15:26:53.000+00:00",
                creator: "admin",
                dbSortType: null,
                endTime: null,
                ids: null,
                level: "2",
                limit: null,
                page: null,
                parentId: 1,
                selected: true,
                sortFields: null,
                startTime: null,
                updateTime: "2023-03-04T15:26:53.000+00:00",
              }],
              createTime: "2023-03-04T15:13:23.000+00:00",
              creator: "admin",
              dbSortType: null,
              endTime: null,
              ids: null,
              isIndeterminate: false,
              level: "1",
              limit: null,
              page: null,
              parentId: 0,
              indeterminate:true, // 是否子级选中的
              selected: false,  // 是否选中
              sortFields: null,
              startTime: null,
              updateTime: "2023-03-04T15:13:23.000+00:00",
            }
          ],*/
        },
        // 表单验证规则
        rules: {
          taticsName: [
            {
              required: true,
              message: '请输入标题',
              trigger: 'blur'
            }
          ],
          tatics: [
            {
              required: true,
              message: '请选择组词策略',
              trigger: 'blur'
            }
          ]
        },
        // 获取 词头列表
        prefixList:[],
        // 获取词尾列表
        endList:[],
        list:[],
        // 1:词头 2：词尾
        type: 0
      }
    },
    created(){
      this.init()
    },
    activated(){
      if(this.$route.query.form){
        this.form = this.$route.query.form
        console.log("this.form.hashtag",this.form.hashtag)
        if(this.form.hashtag){
          // this.hashtagList=this.form.hashtag.split(',')
          // this.hashtagList= JSON.parse(this.form.hashtag)
          this.hashtagList= this.form.hashtag //编辑列表转了，因此回显不需要再转
        }
        else{
          this.hashtagList=[]
        }
        console.log('this.hashtagList',this.hashtagList)


        console.log("this.form.tatics -======",this.form.tatics )
        // this.form.tatics=this.form.tatics.toString()
        // this.form.tatics.split('')
        let id=[]
        id.push(Number(this.form.tatics))
        this.form.tatics=id
        console.log("created=====this.form.tatics -======",this.form.tatics )
        console.log("created=====this.form -======",this.form )
      }
      else{
        // 清空表单
        this.form={
          username:this.$store.state.user.info.username,
          // provinceList:[], 修改，需展示
          platform:1,
          region:'',
          head:'',
          body:'',
          suffix:'',
          hashtag:'',
          tatics:[],
          taticsName:''
        }
        this.hashtagList=[]

      }
    },
    /*watch:{
      '$route'(val, from) {//监听到路由（参数）改变
        // 拿到目标参数 val.query.typeCode 去再次请求数据接口
        console.log("路由切换=====",this.$route.query.form)
        // seo
        if(this.$route.query.form){
          this.form = this.$route.query.form
          console.log("this.form.tatics -======",this.form.tatics )
          // this.form.tatics=this.form.tatics.toString()
          // this.form.tatics.split('')
          let id=[]
          id.push(Number(this.form.tatics))
          this.form.tatics=id
          console.log("created=====this.form.tatics -======",this.form.tatics )
          console.log("created=====this.form -======",this.form )
        }
      }
    },*/
    methods:{
      // 多选框 选中
      handleCheckedCitiesChange(value) {
        console.log('value', value)
        // 设置‘单选’，删除非选中的 （注意！！）
        if(this.form.tatics.length > 1){
          this.form.tatics.splice(0,1)
        }
        console.log('this.form.tatics', this.form.tatics)
        // let checkedCount = value.length;
        // this.checkAll = checkedCount === this.cities.length;
        // this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
      },
      // 城市选择
      /*region:市级文字，以逗号间隔，
      * screenList */
      cityClick(region,screenList){
        this.form.region=region
        return
        console.log("主页返回region,screenList======",region,screenList)
        this.form.provinceList=screenList
        console.log("this.form.region",this.form.region)
      },
      // 获取从弹出框 获取的所有值
      // all：用户去重后的‘词头’数据； checkAll：子组件选择的‘词头’数据 ； listAll：展示的所有‘词头’数据
      checkedAll(all,checkAll,listAll){
        this.form.head =  all && this.form.head  ? all + this.form.head : all && !this.form.head ? all : this.form.head
        // this.form.head = all ? all + this.form.head : this.form.head
        var array = this.form.head .split`,`;
        let newArr= this.wordFun(array,checkAll,listAll)
        this.form.head=newArr.toString()
      },
      // 选择的‘词头’和总数据 去不同
      checkClick(checkAll,item,index,array){
        checkAll.find(i => i.content === item) ? void 0 : delete array[index] ;
      },

      endAll(all,checkAll,listAll){
        this.form.suffix = all && this.form.suffix  ? all + this.form.suffix : all && !this.form.suffix ? all : this.form.suffix
        var array = this.form.suffix .split`,`;
        // for(let i=0;i<array.length;i++){
        //   // 筛选出不同的‘词尾’，将不同的‘词尾’赋值和选择的总数据做对比，获取共同值，或者说，如果i的值不包含在总的数据中，则上传item
        //   listAll.find(x => x.content === array[i]) ? this.checkClick(checkAll,array[i],i,array) : void 0
        // }
        // var newArr = array.filter(item => item && item.trim())
        let newArr= this.wordFun(array,checkAll,listAll)
        this.form.suffix=newArr.toString()

        console.log("form长词尾—+++++++", this.form.suffix)
      },

      // 话题弹框烦
      hashtagClick(info,index){
        if(index==-1){
          this.hashtagList.push(info)
        }
        else{
          // this.$set(this.hashtagList[index],index,info)
          this.hashtagList[index]=info
          this.$forceUpdate() // 强制刷新页面
        }
        console.log("info",info,"hashtagList",this.hashtagList,'index',index)

      },

      wordFun(array,checkAll,listAll){
        for(let i=0;i<array.length;i++){
          // 筛选出不同的‘词头’，将不同的‘词头’赋值和选择的总数据做对比，获取共同值，或者说，如果i的值不包含在总的数据中，则上传item
          listAll.find(x => x.content === array[i]) ? this.checkClick(checkAll,array[i],i,array) : void 0
        }
        console.log('array',array)
        array.filter(function (item,index) {
          if(!item || item=='undefined'){
            console.log("item && item.trim()",item ,index)
            array.splice(index,1);
          }
        })
        return array
      },
      init(){
        //  type 查询的类型 1词头 2尾词  【默认SEO词库查询】
        seodefaultList(1)
          .then((data) => {
            this.prefixList = data.data
            console.log("查询关键词词头data=======",this.prefixList)
          })
          .catch((e) => {
            this.$message.error(e.msg);
          });
        seodefaultList(2)
          .then((data) => {
            this.endList=data.data
            console.log("查询关键词词尾data=======",this.endList)
          })
          .catch((e) => {
            this.$message.error(e.msg);
          });
        // 查询代理区域
        let parems = {}
        areaAll(parems)
          .then((data) => {
            let list = data.data
            /*
            * 首先，筛选出parentId为0的，生成对象，并增加isIndeterminate:false（不确定因素）和selected:false 属性
            * 其次，筛选parentId为0的id 相等的城市
            * 将筛选出来的城市放入名为‘country’的数组，并在其对象数组下加入selected: false
            * 进行打印是否正确
             */
            // 筛选跟级城市
            this.cityList = list.filter((item) => item.parentId===0)
            for(let i=0 ;i<this.cityList.length;i++){
              this.$set(this.cityList[i], 'country', [])
              this.$set(this.cityList[i], 'selected', false)
              this.$set(this.cityList[i], 'isIndeterminate', false)
              for(let j=0 ;j<list.length;j++){
                this.$set(list[j], 'selected', false)
                if(this.cityList[i].areaId == list[j].parentId){
                  this.cityList[i].country.push(list[j])
                }
              }
            }
            console.log("查询代理区域data=======",this.cityList)



          })
          .catch((e) => {
            this.$message.error(e);
          });
        console.log("this.form============",this.form)

      },
      // 插入城市
      addCity(){
        this.areaShow=true
        this.$refs['citys'].show()
      },
      //插入默认词头
      prefixClick(){
        console.log('插入默认词头',this.form.head)
        this.$refs['prefixShow'].show()

      },
      //插入默认长尾词
      endClick(){
        this.$refs['prendShow'].show()
      },

      //查看单个话题
      lookTag(item,index){
        this.$refs['addShow'].show(item,index)
      },

      //删除单个话题
      delTag(index){
        this.hashtagList.splice(index,1)
      },
      //添加多组话题
      addTitle(){
        this.$refs['addShow'].show()
      },

      // 确定保存
      save(){
        if(!this.form.taticsName){
          this.$message.error('请输入标题');
          return
        }
        else if(!this.form.tatics || this.form.tatics==""){
          this.$message.error('请选择组词策略');
          return
        }

        else if(!this.form.region && this.form.tatics==3
          ||!this.form.region && this.form.tatics==4
          ||!this.form.region && this.form.tatics==5
          ||!this.form.region && this.form.tatics==7
        ){
          this.$message.error('请选择区域');
          return
        }
        else if(!this.form.head && this.form.tatics==1
          ||!this.form.head && this.form.tatics==4
          ||!this.form.head && this.form.tatics==6
          ||!this.form.head && this.form.tatics==7
        ){
          this.$message.error('请选择/输入词头');
          return
        }
        else if(!this.form.body){
          this.$message.error('请输入主词');
          return
        }
        else if(!this.form.suffix && this.form.tatics==2
          ||!this.form.suffix && this.form.tatics==5
          ||!this.form.suffix && this.form.tatics==6
          ||!this.form.suffix && this.form.tatics==7){
          this.$message.error('请选择/输入长尾词');
          return
        }
        // 添加话题，需删除——有问题
        else if(!this.form.hashtag){
          this.$message.error('请添加话题组');
          return
        }
        else{
          console.log('this.form=======',this.form)
          // 数组转字符串逗号拼接
          this.form.tatics =  this.form.tatics.join(",")
          console.log(this.form.tatics)
          //为空删除
          if(!this.form.region){
            delete this.form.region
          }
          if(!this.form.head){
            delete this.form.head
          }
          if(!this.form.suffix){
            delete this.form.suffix
          }
          if(this.hashtagList.length>0){
            // this.form.hashtag=this.hashtagList.join(',')
            this.form.hashtag=JSON.stringify(this.hashtagList);
          }
          if(!this.form.hashtag){
            delete this.form.hashtag
          }
          console.log("确定保存this.form=======",this.form)
          let apiName=this.form.id?updateSeo:addSeo
          apiName(this.form)
            .then((data) => {
              // this.$message.success(data.msg)
              this.$message.success('保存成功！')
              // 清空表单
              this.form={
                username:this.$store.state.user.info.username,
                // provinceList:[], 修改，需展示
                platform:1,
                region:'',
                head:'',
                body:'',
                suffix:'',
                hashtag:'',
                tatics:[],
                taticsName:''
              }
              this.hashtagList=[]
              console.log("清空form-----",this.form)
            })
            .catch((e) => {
              this.$message.error(e);
            });
        }

        /*this.$refs.form.validate((valid) => {
          if (valid) {
          } else {
            return false;
          }
        });*/
      }
    }

  }
</script>

<style scoped lang="less">
  /deep/.el-textarea__inner:focus {
    // el-input输入时设置边框颜色
    border: #000 2px solid;
    box-sizing: border-box;
  }
  /deep/ .el-textarea__inner{
    border: none;
  }
  /deep/ .el-button--primary {
    background: #0C91F3;
  }
  /deep/ .el-button--medium{
    margin-top: 15px;
    width: 150px;
    height: 33px;
    border-radius: 2px;
  }
  /deep/.input :focus {
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    // el-input输入时设置边框颜色
    border: #11be59 1px solid;
  }
  .keyword-title{
    font-size: 20px;
    line-height: 24px;
    margin-right: 20px;
    color: #000000;
  }
  .set-hint{
    margin: 12px 0 16px;
    padding: 14px 11px;
    background: #DDF0FF;
    border-radius: 5px;
    line-height: 28px;
    color: #1E6CEB;
  }
  .content{
    padding: 12px 11px 25px;
    margin-bottom: 18px;
    border: 1px solid #F5F5F5;
    overflow: hidden;
    .el-width{
      margin:0px 0 35px;
      width: 18%;
      .key-border{
        width: 100%;
        border: 1px solid #D9D9D9;
        box-sizing: border-box;
        -moz-box-sizing: border-box;
        border-radius: 5px;
        overflow: hidden;
        .content-title{
          background: #FAFAFC;
          height: 59px;
          div:first-child{
            margin-bottom: 5px;
          }
        }
        .input-border{
          border: #11be59 2px solid;
          box-sizing: border-box;
          -moz-box-sizing: border-box;
          border-radius: 5px;
          z-index:99
        }
        .none-border{
          border:none
        }

        .all-hashtag{
          height: 221px;
          margin: 20px 0;
          /* 设置超出滚动 */
          overflow-x:auto;
          .input-hashtag{
            margin: 0px 20px 10px;
            background: #f2f2f2;
            padding: 10px;
            border-radius: 3px;
            width: calc(100% - 125px);
            height: 14px;
            /* 超出滚动的关键，没有它元素会自动缩小，不会滚动 */
            flex-shrink: 0;
            /*width: calc(100% - 40px);*/
          }
          .edit-hashtag{
            z-index: 999;
            background: #f2f2f2;
            height: 14px;
            width: 34px;
            padding: 10px 0;
            position: absolute;
            top: 0;
            right: 54px;

            /* 超出滚动的关键，没有它元素会自动缩小，不会滚动 */
            flex-shrink: 0;
          }
          .del-hashtag{
            height: 14px;
            background: #f2f2f2;
            z-index: 999;
            width: 34px;
            padding: 10px 0;
            position: absolute;
            top: 0;
            right: 20px;

            /* 超出滚动的关键，没有它元素会自动缩小，不会滚动 */
            flex-shrink: 0;
          }        }

      }
    }
  }
  .save-btn{
    margin-left: calc( 50% - 70px);
    width: 140px;
    height: 38px;
    background: linear-gradient(180deg, #0E8FF3 0%, #1D6FEC 100%);
    border-radius: 2px;
    font-size: 16px;
    color: #FFFFFF;
  }
</style>
